<!-- 视频管理（分组） -->
<template>
  <ContainerSlot>
    <template slot="searchModule">
      <SearchForm :labelWidth="'120px'" :formConfig="formConfig" :formData="formData" :slotList="slotList" ref="ruleForm">
        <template slot="searchBtn">
          <el-button type="primary" @click.prevent="goSearch()">查询</el-button>
        </template>
        <template slot="resetBtn">
          <el-button @click.prevent="resetForm()">重置</el-button>
        </template>
      </SearchForm>
    </template>
    <template slot="operationModule">
      <div style="width: 100%;">
        <CategoryBar :categoryList="categoryList" @categoryBar="categoryBar" />
        <div style="text-align: right; margin-top: 10px;">
          <el-button v-show="!groupVisible" @click="backGroup">返回</el-button>
          <el-button v-show="auditStatus == 1 && !groupVisible" type="primary" @click="submitSort" style="float: left;">
            保存视频顺序
          </el-button>
          <el-button v-show="auditStatus == 0" type="primary" @click="add">
            <i class="el-icon-upload"></i>
            上传视频
          </el-button>
          <el-button v-show="!groupVisible" :disabled="!checkActive" type="danger" @click="delVideo()">
            <i class="el-icon-delete"></i>
            删除
          </el-button>
          <!-- <el-button v-show="!groupVisible" :disabled="!checkActive" type="primary" @click="approved">通过审核</el-button>
            <el-button v-show="!groupVisible" :disabled="!checkActive" type="warning" @click="unApproved">不通过审核</el-button> -->
        </div>
      </div>
    </template>
    <template slot="contentModule">
      <div v-show="groupVisible" v-loading="loading" class="video-box video-group-box">
        <el-checkbox-group v-model="checkList" v-for="item, index in videoGroupList" :key="item.vedioGroupId">
          <!-- v-show="item.videoList.length" -->
          <el-checkbox :label="item.vedioGroupId">
            <div class="video-card" @click.prevent="loadVideoDetail(item.vedioGroupId)">
              <div class="header">
                <div class="group-title">分组名称：{{ item.name }}</div>
              </div>
              <div class="group-content">
                <div class="video-title">视频列表：</div>
                <div class="video-content">
                  <div v-for="ite, i in item.titles" :key="ite.vedioId">{{ i + 1 }}. {{ ite }}</div>
                </div>
              </div>
            </div>
          </el-checkbox>
        </el-checkbox-group>
        <div class="noData" v-show="videoGroupList.length == 0">
          暂无数据
        </div>
      </div>
      <div v-show="!groupVisible" v-loading="loading" class="video-box">
        <draggable v-model="videoList">
          <el-checkbox-group v-model="checkList" v-for="item, index in videoList" :key="item.vedioId"
            @change="handleSelectionChange">
            <el-checkbox :label="item.vedioId">
              <div class="video-card draggable" @click.prevent>
                <div class="header">
                  <div class="info">
                    <toolTip :tipContent="auditStatus == 0 ? item.createTime :
                      `审核日期：${item.auditDate} 审核人：${item.auditUserName}`">
                      <span v-show="auditStatus == 0">{{ item.createTime }}</span>
                      <span class="mr-20" v-show="auditStatus != 0">审核日期：{{ item.auditDate }}</span>
                      <span v-show="auditStatus != 0">审核人：{{ item.auditUserName }}</span>
                    </toolTip>
                    <span class="delete" @click="delVideo(item)" v-show="auditStatus != 2">
                      <i class="el-icon-delete"></i>
                    </span>
                  </div>
                  <div class="title">{{ (currentPage - 1) * pageSize + index + 1 }}. {{ item.title }}</div>
                </div>
                <div class="videoShade" @click="addressUrl = item.addressUrl">
                  <i class="el-icon-video-play"></i>
                </div>
                <div v-show="auditStatus == 2" class="reason">
                  <toolTip :tipContent="`审核未通过原因：${item.auditRemark}`">
                    审核未通过原因：{{ item.auditRemark }}
                  </toolTip>
                </div>
                <div class="edit" v-show="auditStatus == 2">
                  <el-button type="warning" size="mini" @click="handleEdit(item)">
                    <i class="el-icon-edit"></i>
                    修改
                  </el-button>
                  <el-button class="opt" type="danger" size="mini" @click="delVideo(item)">
                    <i class="el-icon-delete"></i>
                    删除
                  </el-button>
                </div>
              </div>
            </el-checkbox>
          </el-checkbox-group>
          <div class="noData" v-show="videoList.length == 0">
            暂无数据
          </div>
        </draggable>
      </div>
      <div class="videoBox" v-if="addressUrl">
        <div class="close" style="color: #ffffff; cursor: pointer;" @click="closeVideo()">关闭
        </div>
        <!-- <video id="myVideo" class="videoItem video-js vjs-default-skin vjs-big-play-centered" :controls="true"
          :loop="false" :muted="false" preload="auto" :showPlay="true">
          <source :src='addressUrl'>
        </video> -->
        <Video id="mine_videoItem" class="videoItem" :videoSrc="addressUrl" :width="'100%'" :height="'100%'"
          :controls="true" :loop="false" :muted="false" preload="auto" :showPlay="true" :playWidth="96" zoom="contain">
        </Video>
        <!-- <Video class="videoItem" :videoSrc="'http://192.168.20.103:8888/api/video/test'" :width="'100%'" :height="'100%'"
          :controls="true" :loop="false" :muted="false" preload="auto" :showPlay="true" :playWidth="96"
          :playbackRates="[0.7, 1.0, 1.5, 2.0]" zoom="contain">
        </Video> -->
        <!-- <video-player ref="videoPlayer" :options="playerOptions" @ready="onPlayerReady"></video-player> -->
      </div>
      <el-dialog :close-on-click-modal='false' :title="dialogTitle + '视频'" :visible.sync="dialogFormVisible"
        :before-close="cancel" width="30%">
        <el-form ref="addForm" label-position="right" :model="addForm" class="el-form" :rules="rules" label-width="120px">
          <el-form-item label="视频标题:" prop="title" class="w100p">
            <el-input v-model="addForm.title" clearable />
          </el-form-item>
          <el-form-item label="视频分类:" prop="vedioTypeId" class="w100p">
            <el-select v-model="addForm.vedioTypeId" clearable placeholder="请选择视频分类" @change="vedioTypeChange"
              style="width: 100%;">
              <el-option v-for="item in videoTypeList" :key="item.vedioTypeId" :label="item.name"
                :value="item.vedioTypeId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="视频分组:" prop="vedioGroupId" class="w100p">
            <el-select v-model="addForm.vedioGroupId" :disabled="!addForm.vedioTypeId" clearable placeholder="请选择视频分组"
              style="width: 100%;">
              <el-option v-for="item in videoGroupArr" :key="item.vedioGroupId" :label="item.name"
                :value="item.vedioGroupId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="视频:" prop="addressUrl" class="w100p">
            <Upload v-if="dialogFormVisible" :imgUrlList="addForm.addressUrl" @getFiles="getFiles" :limit="1" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save">
            保 存
          </el-button>
          <el-button v-show="auditStatus == 2" class="zh-button-two" type="primary" @click="saveAudit">
            再次提交审核
          </el-button>
        </div>
      </el-dialog>
    </template>
    <template slot="footerModule">
      <el-pagination v-show='groupVisible' @size-change="handleSizeChangeGroup" @current-change="handleCurrentChangeGroup"
        :current-page="currentPageGroup" background :page-size="pageSizeGroup" :page-sizes="[10, 20, 30]"
        layout="sizes, prev, pager, next, jumper" :total="totalGroup">
      </el-pagination>

      <el-pagination v-show="!groupVisible" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" background :page-size="pageSize" :page-sizes="[10, 20, 30]"
        layout="sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      </el-pagination>
      </el-pagination>
    </template>
  </ContainerSlot>
</template>

<script>
import ContainerSlot from '@/components/Container'
import SearchForm from '@/components/Form'
import Table from '@/components/Table'
import CategoryBar from "@/components/CategoryBar"
import Video from "../video-management-ungroup/components/video"
import Upload from "../video-management-ungroup/components/upload"
import toolTip from "../video-management-ungroup/components/toolTip"
import draggable from "vuedraggable"

import videoTypeApi from "@/api/breed-aquatics-popular/knowledge-base-management/video-type-management"
import videoGroupApi from "@/api/breed-aquatics-popular/knowledge-base-management/video-group-management"
import videoApi from "@/api/breed-aquatics-popular/knowledge-base-management/video-management"
import axios from "axios";
import Cookies from "js-cookie";


export default {
  name: '',
  components: { ContainerSlot, SearchForm, Table, CategoryBar, Video, Upload, toolTip, draggable },
  data () {
    return {
      addressUrl: '',
      loading: false,
      groupVisible: true,
      checkActive: false,
      // 表单配置
      formConfig: [
        {
          label: '视频关键词',
          prop: 'name',
          type: 'input',
          width: '150px'
        },
        {
          label: '发布时间',
          prop: 'date',
          type: 'daterange',
          width: '240px'
        }
      ],
      //插槽
      slotList: [{
        slotName: 'searchBtn'
      },
      {
        slotName: 'resetBtn'
      }],
      // 表单数据
      formData: {
        name: '',
        date: [],
      },
      categoryList: [
        { id: 1, mark: 'status', name: "待审核视频", value: 0 },
        { id: 2, mark: 'status', name: "已通过审核视频", value: 1 },
        { id: 3, mark: 'status', name: "未通过审核视频", value: 2 },
      ],
      auditStatus: 1,
      // 新增编辑
      dialogTitle: '',
      dialogFormVisible: false,
      addForm: {
        title: '',
        vedioGroupId: '',
        addressUrl: '',
      },
      rules: {
        title: [
          { required: true, message: '请输入视频标题', trigger: ['change', 'blur'] },
        ],
        vedioTypeId: [
          { required: true, message: '请选择视频分类', trigger: ['change', 'blur'] },
        ],
        vedioGroupId: [
          { required: true, message: '请选择视频分组', trigger: ['change', 'blur'] },
        ],
        addressUrl: [
          { required: true, message: '请上传视频', trigger: ['change', 'blur'] },
        ],
      },
      addressUrlList: [],
      videoGroupArr: [],
      videoGroupAllArr: [],
      // 视频分组列表
      videoGroupList: [],
      videoTypeList: [],
      // 视频列表
      videoList: [],
      checkList: [],
      // 分页
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 分组分页
      totalGroup: 0,
      currentPageGroup: 1,
      pageSizeGroup: 10,
      RangeNum: 1024 * 1024 * 5,       //1MB
      startNum: 0,
      fileSize: 0,
      fileNum: 0
    }
  },
  watch: {
    dialogFormVisible (v) {
      if (v) {
        this.$nextTick(() => {
          this.$refs.addForm.clearValidate()
          this.addForm = {
            title: '',
            vedioGroupId: '',
            addressUrl: '',
          }
        })
      }
    }
  },
  mounted () {
    this.loadTypeList()
    // this.getVideo();
  },
  methods: {
    closeVideo () {
      var videoElement = document.querySelector('#mine_videoItem video');
      videoElement.pause();
      videoElement.removeAttribute('src'); // empty source
      videoElement.load();
      this.turnOffSrc();
      this.addressUrl = null
    },
    //切断分段视频
    turnOffSrc () {
      axios.get(this.addressUrl, {
        headers: { token: Cookies.get("token"), Range: `bytes=${2 * 1024 * 1024 * 1024}-` }, responseType: 'blob'
      })
    },
    getBase64 (data, type) {
      const blob = new Blob([data], { type: type }); //类型一定要写！！！
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    // 分组分页
    handleCurrentChangeGroup (e) {
      this.currentPage = e
      this.goSearch()
    },
    handleSizeChangeGroup (e) {
      this.pageSize = e
      this.goSearch()
    },
    // 分页
    handleCurrentChange (e) {
      this.currentPage = e
      this.goSearch()
    },
    handleSizeChange (e) {
      this.pageSize = e
      this.goSearch()
    },
    categoryBar (item) {
      this.auditStatus = ''
      if (item.mark === 'status') this.auditStatus = item.value
      this.currentPage = 1
      this.goSearch()
    },
    resetForm () {
      this.$refs.ruleForm.resetForm()
      this.goSearch()
    },
    // 搜索
    goSearch () {
      this.currentPage = 1
      this.updataContent()
    },
    updataContent () {
      if (this.groupVisible) {
        this.queryPageList()
      } else {
        this.loadVideoDetail(this.groupId)
      }
    },
    loadTypeList () {
      videoTypeApi.queryByCondition({ name: '' }).then(res => {
        this.videoTypeList = res.data
      })
      videoGroupApi.queryByCondition({ name: '' }).then(res => {
        this.videoGroupAllArr = res.data
        this.videoGroupArr = [...this.videoGroupAllArr]
      })
    },
    vedioTypeChange () {
      this.addForm.vedioGroupId = ''
      if (this.addForm.vedioTypeId) {
        let list = []
        this.videoGroupAllArr.map(el => {
          el.vedioTypeId == this.addForm.vedioTypeId && list.push(el)
        })
        this.videoGroupArr = list
      } else {
        this.videoGroupArr = [...this.videoGroupAllArr]
      }
    },
    // 获取视频分组
    queryPageList () {
      this.loading = true
      this.videoGroupList = []
      videoApi.queryGroupPageByCondition({
        page: this.currentPageGroup,
        size: this.pageSizeGroup,
        condition: {
          auditStatus: this.auditStatus,
          title: this.formData.name,
          beginTime: this.formData.date && this.formData.date[0] && this.formData.date[0] + ' 00:00:00',
          endTime: this.formData.date && this.formData.date[1] && this.formData.date[1] + ' 23:59:59'
        }
      }).then(res => {
        let { data } = res
        this.videoGroupList = data.content
        this.totalGroup = data.totalElements
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 视频顺序
    submitSort () {
      let i = (this.currentPage - 1) * this.pageSize + 1
      this.videoList.map(el => {
        el.seqGroup = i
        i++
      })

      videoApi.edits(this.videoList).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.updataContent()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 获取视频
    loadVideoDetail (id) {
      this.loading = true
      this.videoList = []
      this.groupId = id
      this.groupVisible = false
      videoApi.queryPageByCondition({
        page: this.currentPage,
        size: this.pageSize,
        condition: {
          vedioGroupId: id,
          auditStatus: this.auditStatus,
          title: this.formData.name,
          beginTime: this.formData.date && this.formData.date[0] && this.formData.date[0] + ' 00:00:00',
          endTime: this.formData.date && this.formData.date[1] && this.formData.date[1] + ' 23:59:59'
        }
      }).then(res => {
        let { data } = res
        this.videoList = data.content
        this.total = data.totalElements
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    backGroup () {
      this.groupVisible = true
      this.goSearch()
    },
    // 选择视频
    handleSelectionChange (list) {
      if (list && list.length > 0) {
        this.checkActive = true;
      } else this.checkActive = false;
    },
    // 审核
    approved () {
      this.$confirm("确定通过审核吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      }).then(() => {

      })
    },
    unApproved () {
      this.$prompt('不通过原因', '不通过审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator (value) { if (!value || !value.trim()) return false },
        inputErrorMessage: '请输入不通过原因'
      }).then(({ value }) => {

      })
    },
    // 删除
    delVideo (row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      }).then(() => {
        let idList = (row ? [row.vedioId] : this.checkList).join(',')
        videoApi.delList({ idList }).then(res => {
          if (res.code == 200) {
            this.$message.success(res.msg)
            this.updataContent()
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    // 上传视频
    add () {
      this.openDialog('add')
    },
    handleEdit (row) {
      this.addForm = { ...row }
      this.openDialog('edit')
    },
    openDialog (type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "上传" : "编辑";
      this.nowChanceStau = type;
    },
    getFiles (fileList) {
      console.log(fileList)
      if (fileList.length && fileList[0].url) {
        this.addForm.addressUrl = fileList[0].url
      } else {
        this.addForm.addressUrl = ''
      }
      this.$refs.addForm.validateField(['addressUrl'], () => { })
    },
    save () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          videoApi[this.nowChanceStau](this.addForm).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.cancel()
              this.updataContent()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    saveAudit () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let param = { ...this.addForm }
          param.auditStatus = 0
          videoApi.editAndAudit(param).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.cancel()
              this.updataContent()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    cancel () {
      this.$refs.ruleForm.resetForm()
      this.dialogFormVisible = false;
      this.addForm = {
        title: '',
        vedioGroupId: '',
        addressUrl: '',
      };
    },
  }
}
</script>

<style lang="scss" scoped>
.noData {
  width: 100%;
  margin-top: 30px;
  text-align: center;
  font-size: 16px;
}

::v-deep .video-box {
  display: flex;
  flex-wrap: wrap;
  height: 100%;
  overflow: auto;

  &>div {
    width: 100%;
  }

  &.video-group-box {
    .el-checkbox-group {
      background: #edf7ff;
      padding: 10px 10px 0;
    }

    .el-checkbox__input {
      display: none;
    }
  }

  .el-checkbox-group {
    display: inline-block;
    width: calc((100% - 80px) / 4);
    min-width: 270px;
    height: fit-content;
    box-shadow: 0 3px 6px 1px rgba(0, 0, 0, .2);
    margin: 10px;
    border-radius: 5px;
    overflow: hidden;

    &:nth-of-type(4n+0) {
      margin-right: 0;
    }

    .el-checkbox__input {
      position: absolute;
      top: 9px;
      left: 5px;

      .el-checkbox__inner {
        border-radius: 50%;
        width: 20px;
        height: 20px;

        &::after {
          left: 7px;
          top: 4px;
        }
      }
    }

    .el-checkbox__label {
      padding-left: 0;
      width: 100%;
    }

    .el-checkbox {
      width: 100%;
    }
  }

  .video-card {
    width: 100%;
    cursor: auto;

    &.draggable {
      cursor: all-scroll;
    }

    .header {
      padding: 10px;
      user-select: text;

      .info {
        height: 20px;
        padding-left: 30px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        .delete {
          display: inline-block;
          color: #fff;
          background: #fd5a58;
          cursor: pointer;
          width: 20px;
          height: 20px;
          text-align: center;
          position: absolute;
          right: 0;
          top: 0;
          border-bottom-left-radius: 5px;
        }
      }

      .title {
        margin-top: 10px;
      }

      // .group-title { 
      //   padding-left: 30px;
      // }
    }

    .content {
      width: 100%;
      text-align: center;
      padding: 0 10px;
    }

    .group-content {
      width: 100%;
      height: 200px;
      padding: 0 10px;
      margin: 10px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      .video-title {
        margin-bottom: 5px;
      }

      .video-content {
        line-height: 26px;

        &>div {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .reason {
      text-align: left;
      padding: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .edit {
      text-align: right;
      padding: 0 10px 5px 0;
    }
  }
}

.videoBox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #333333b2;
  z-index: 99999;

  .close {
    position: absolute;
    right: 30px;
    top: 30px;
  }

  .videoItem {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    height: 80%;
  }
}

.videoShade {
  width: calc(100% - 20px);
  height: 160px;
  margin: 10px;
  background: #333333;
  color: #5f5f5f;
  font-size: 38px;
  text-align: center;
  line-height: 160px;
  cursor: pointer;
}
</style>
